package org.example.fastproject.web.sys.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.fastproject.core.bean.PageParam;
import org.example.fastproject.core.bean.SysUserDetails;
import org.example.fastproject.core.exception.Asserts;
import org.example.fastproject.core.utils.FileUtil;
import org.example.fastproject.core.utils.SecurityUtil;
import org.example.fastproject.web.sys.model.SysFile;
import org.example.fastproject.web.sys.mapper.SysFileMapper;
import org.example.fastproject.web.sys.service.SysFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * <p>
 * 文件记录表 服务实现类
 * </p>
 *
 * @author 王海舟
 * @since 2023-02-01 10:56:41
 */
@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {

    @Override
    public Long upload(MultipartFile multipartFile,boolean isPublic) throws IOException {
        String realName = multipartFile.getOriginalFilename();
        Long size = multipartFile.getSize();
        String suffix = FileUtil.getSuffix(realName);
        //写入本地文件系统
        String name = FileUtil.upload(multipartFile,isPublic);
        //登录用户
        SysUserDetails user = SecurityUtil.getUser();
        //存储文件记录
        SysFile sysFile = new SysFile();
        sysFile.setName(name);
        sysFile.setRealName(realName);
        sysFile.setSize(size);
        sysFile.setSuffix(suffix);
        sysFile.setCreateUser(user.getId());
        sysFile.setCreateTime(user.getDate());
        if(isPublic)
            sysFile.setPath("/public/"+name);
        this.save(sysFile);
        return sysFile.getId();
    }

    @Override
    public void download(Long fileId) throws IOException {
        //获取文件名
        SysFile sysFile = this.getById(fileId);
        if(Objects.isNull(sysFile))
            Asserts.fail("文件记录不存在");
        String name = sysFile.getName();
        HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                .getResponse();
        FileUtil.download(name,response);
    }

    @Override
    public Page<SysFile> page(PageParam param) {
        Page page = new Page(param.getNum(),param.getSize());
        this.page(page);
        return page;
    }
}
